package org.ysh.core.utils;

import org.apache.poi.ss.formula.functions.T;

import java.io.*;
import java.nio.file.Files;
import java.util.UUID;

/**
 * IO流工具类
 */
public class StreamUtils {

    private static String TEMP_PATH = "./";

    /**
     * 输入流内容转出为输出流
     * @param in
     * @param out
     * @throws IOException
     */
    public static void inputToOutput(InputStream in, OutputStream out) throws IOException {
        byte[] buffer = new byte[8*1024];
        int len;
        while((len = in.read(buffer)) != -1){
            out.write(buffer,0,len);
        }
    }

    /**
     * 拷贝输入流到另一个输入流
     * @param src
     * @throws IOException
     */
    public static File inputStreamToTempFile(InputStream src) throws IOException {
        File tempFile = new File(TEMP_PATH + File.separator + UUID.randomUUID());
        try(OutputStream outputStream = Files.newOutputStream(tempFile.toPath())){
            inputToOutput(src, outputStream);
        }
        return tempFile;
    }

    /**
     * 拷贝文件到一个临时路径
      * @param src
     * @return
     * @throws IOException
     */
    public static File normalFileToTempFile(File src) throws IOException {
        File tempFile = new File(TEMP_PATH + File.separator + UUID.randomUUID());
        try(RandomAccessFile read = new RandomAccessFile(src,"r");
            RandomAccessFile write = new RandomAccessFile(tempFile,"rw")){
            read.getChannel().transferTo(0,read.length(),write.getChannel());
        }
        return tempFile;
    }
}
